package com.kylin.system.common.utils;

/**
 * @author wuhao
 * @version 1.0 - 2024/11/21
 */
import java.security.SecureRandom;
import java.util.Random;

public class PasswordGenerator {

    private static final String UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String LOWER_CASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String DIGITS = "0123456789";
    private static final String SPECIAL_CHARACTERS = "@#~";
    private static final String ALL_CHARACTERS = UPPER_CASE + LOWER_CASE + DIGITS + SPECIAL_CHARACTERS;
    private static final Random RANDOM = new SecureRandom();

    /**
     * 生成指定长度的随机密码。
     * @param length 密码的长度
     * @return 生成的密码字符串
     */
    public static String generatePassword(int length) {
        if (length < 1) throw new IllegalArgumentException("Length must be greater than 0");

        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            // 从所有字符中随机选择一个字符
            int randomIndex = RANDOM.nextInt(ALL_CHARACTERS.length());
            sb.append(ALL_CHARACTERS.charAt(randomIndex));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        // 测试生成密码
        String password = generatePassword(12); // 可以改变这个数字来改变密码的长度
        System.out.println("Generated Password: " + password);
    }
}
